package com.samnative.pineapple.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.shashank.sony.fancytoastlib.FancyToast;
import com.samnative.pineapple.main.R;
import com.samnative.pineapple.utils.PackageUtils;
import com.samnative.pineapple.utils.ViewHelper;

/**
 * 选择第三方地图
 *
 * @author wangyang
 */
public class ChooseMapPop extends PopupWindow {

    private Context context;
    /**
     * 有效区域
     */
    private View view;
    /**
     * 阴影层
     */
    private View viewShade;
    /**
     * 商家名称
     */
    private String BusinessName;
    /**
     * 商家坐标
     */
    private String lat, lng;


    public ChooseMapPop(final Context context, String BusinessName, String lat,
                        String lng) {
        this.context = context;
        this.BusinessName = BusinessName;
        this.lat = lat;
        this.lng = lng;
        LayoutInflater inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.pop_choose_map, null);
        viewShade = view.findViewById(R.id.v_pop_shade);
        view.findViewById(R.id.pop_close).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });

        // 点击有效区域外则退出pop
        view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int hight = view.findViewById(R.id.pop_layout).getTop();
                int point = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (point < hight) {
                        dismiss();
                    }
                }
                return true;
            }
        });

        view.findViewById(R.id.tv_tencent_map).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dismiss();
                        openTencentMap(context, 0, 0, "", Double.parseDouble(lat), Double.parseDouble(lng), BusinessName);
                    }
                });
        view.findViewById(R.id.tv_gaode_map).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dismiss();
                        openGaoDeNavi(context, 0, 0, "", Double.parseDouble(lat), Double.parseDouble(lng), BusinessName);
                    }
                });
        view.findViewById(R.id.tv_baidu_map).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dismiss();
                        openBaiDuNavi(context, 0, 0, "", Double.parseDouble(lat), Double.parseDouble(lng), BusinessName);
                    }
                });

        setContentView(view);
        setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        setHeight(ViewHelper.getWindowRealize((Activity) context).y);
        setFocusable(true);
//        setAnimationStyle(R.style.AnimBottom);
//        setBackgroundDrawable(new ColorDrawable(0x00000000));
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setClippingEnabled(false);
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        // TODO Auto-generated method stub
        super.showAtLocation(parent, gravity, x, y);

    }

    @Override
    public void dismiss() {
        // TODO Auto-generated method stub
        super.dismiss();
    }


    /**
     * 百度转高德
     *
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    public static double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }

    /**
     * 高德、腾讯转百度
     *
     * @param gd_lon
     * @param gd_lat
     * @return
     */
    private static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }


//    /**
//     * 打开高德地图客户端
//     */
//    public void openGaodeMap() {
//        try {
//            Intent intent = Intent
//                    .getIntent("androidamap://viewMap?sourceApplication=appname&poiname="
//                            + BusinessName
//                            + "&lat="
//                            + lat
//                            + "&lon="
//                            + lng
//                            + "&dev=0");
//            if (PackageUtils.isAppInstalled(context, "com.autonavi.minimap")) {
//                context.startActivity(intent);
//            } else {
//                ToastUtils.showShort("未安装高德地图客户端");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//    double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
//    /**
//     * 打开百度地图客户端
//     */
//    public void openBaiduMap() {
//        try {
//            double gg_lat = Double.parseDouble(lat);
//            double gg_lon = Double.parseDouble(lng);
//            // 火星坐标系转百度坐标系
//            double x = gg_lon, y = gg_lat;
//            double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
//            double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
//            double bd_lon = z * Math.cos(theta) + 0.0065;
//            double bd_lat = z * Math.sin(theta) + 0.006;
//
//            Intent intent = Intent
//                    .getIntent("intent://map/marker?location="
//                            + bd_lat
//                            + ","
//                            + bd_lon
//                            + "&title="
//                            + BusinessName
//                            + "&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
//            if (PackageUtils.isAppInstalled(context, "com.baidu.BaiduMap")) {
//                context.startActivity(intent);
//            } else {
//                ToastUtils.showShort("未安装百度地图客户端");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * 打开百度地图导航功能(默认坐标点是高德地图，需要转换)
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public static void openBaiDuNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {

        if (!PackageUtils.isAppInstalled(context, "com.baidu.BaiduMap")) {
            FancyToast.showToast(context,context.getString(R.string.no_baidu_app), FancyToast.WARNING,false);
            return;
        }

        //终点坐标转换
        String uriString = null;
        double destination[] = gaoDeToBaidu(dlat, dlon);
        dlat = destination[0];
        dlon = destination[1];

        StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
        if (slat != 0) {
            //起点坐标转换
            double[] origin = gaoDeToBaidu(slat, slon);
            slat = origin[0];
            slon = origin[1];

            builder.append("origin=latlng:")
                    .append(slat)
                    .append(",")
                    .append(slon)
                    .append("|name:")
                    .append(sname);
        }
        builder.append("&destination=latlng:")
                .append(dlat)
                .append(",")
                .append(dlon)
                .append("|name:")
                .append(dname);
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage("com.baidu.BaiduMap");
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }


    /**
     * 打开高德地图导航功能
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public static void openGaoDeNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {


        if (!PackageUtils.isAppInstalled(context, "com.autonavi.minimap")) {
            FancyToast.showToast(context,context.getString(R.string.no_gaode_app), FancyToast.WARNING,false);
            return;
        }

        String uriString = null;
        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=maxuslife");
        if (slat != 0) {
            builder.append("&sname=").append(sname)
                    .append("&slat=").append(slat)
                    .append("&slon=").append(slon);
        }
        builder.append("&dlat=").append(dlat)
                .append("&dlon=").append(dlon)
                .append("&dname=").append(dname)
                .append("&dev=0")
                .append("&t=0");
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage("com.autonavi.minimap");
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }


    /**
     * 打开腾讯地图
     * params 参考http://lbs.qq.com/uri_v1/guide-route.html
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     *                驾车：type=drive，policy有以下取值
     *                0：较快捷
     *                1：无高速
     *                2：距离
     *                policy的取值缺省为0
     *                &from=" + dqAddress + "&fromcoord=" + dqLatitude + "," + dqLongitude + "
     */
    public void openTencentMap(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {

        if (!PackageUtils.isAppInstalled(context, "com.tencent.map")) {
            FancyToast.showToast(context,context.getString(R.string.no_tencent_app), FancyToast.WARNING,false);
            return;
        }

        String uriString = null;
        StringBuilder builder = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");
        if (slat != 0) {
            builder.append("&from=").append(sname)
                    .append("&fromcoord=").append(slat)
                    .append(",")
                    .append(slon);
        }
        builder.append("&to=").append(dname)
                .append("&tocoord=").append(dlat)
                .append(",")
                .append(dlon);
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage("com.tencent.map");
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }


}
